#include "ECusTableModel.h"
#include <QDebug>

ECusTableModel::ECusTableModel(QObject *parent)
{
    Q_UNUSED(parent)
}

ECusTableModel::~ECusTableModel()
{
    qDebug()<<__FUNCTION__;
}

QVariant ECusTableModel::data(const QModelIndex &index, int role) const
{
    if (role == Qt::DisplayRole) {
        return m_data[index.row()].at(index.column());
    }
    else
    {
        int columnIndex = role - Qt::UserRole - 1;
        QModelIndex modelIndex = this->index(index.row(), columnIndex);
        return m_data[modelIndex.row()].at(modelIndex.column());
    }
}

int ECusTableModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent)
    return m_data.size();
}

int ECusTableModel::columnCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent)
    if(m_data.isEmpty())
        return 0;
    return m_data.at(0).size();
}

QHash<int, QByteArray> ECusTableModel::roleNames() const
{
    QHash<int, QByteArray> roles;
    for(int i = 0;i < m_roles.size();i++)
    {
        roles[Qt::UserRole+i+1] = m_roles.at(i).toLocal8Bit();
    }
    return roles;
}

bool ECusTableModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if(index.isValid() && role > Qt::UserRole){
        int row = index.row();
        int column = index.column();
        m_data[row][column] = value;
        emit dataChanged(index,index);
        return  true;
    }
    return false;
}

QVariant ECusTableModel::rowData(const int row, const QString roleName)
{
    int role = roleNames().key(roleName.toUtf8());
    int column = role-Qt::UserRole-1;
    if(!this->index(row,column).isValid()){
        return false;
    }
    QVariant value = this->data(this->index(row,column),role);
    return value;
}

bool ECusTableModel::setRowData(const int row, const QString roleName, const QVariant newValue)
{
    int role = roleNames().key(roleName.toUtf8());
    int column = role-Qt::UserRole-1;
    if(!this->index(row,column).isValid()){
        return false;
    }
    bool ret = this->setData(this->index(row,column),newValue,role);
    return  ret;
}

void ECusTableModel::insertNewRowData(QVariantList dataList)
{
    beginInsertRows(QModelIndex(),rowCount(),rowCount());
    m_data.push_back(dataList);
    this->insertRow(rowCount());
    endInsertRows();
}

void ECusTableModel::removeRowData(int row)
{
    beginRemoveRows(QModelIndex(),row,row);
    m_data.removeAt(row);
    endRemoveRows();
}

QStringList ECusTableModel::roles() const
{
    return m_roles;
}

void ECusTableModel::setRoles(const QStringList roles)
{
    if(!roles.isEmpty()){
        m_roles = roles;
    }
}

void ECusTableModel::loadData(QList<QVariantList> data)
{
    beginResetModel();
    m_data = data;
    endResetModel();
}
